'use strict';

const webpack = require("webpack");
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssSCSS = require('postcss-scss');
const precss = require('precss');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const copyWebpackPlugin = require('copy-webpack-plugin');
const openBrowserPlugin = require('open-browser-webpack-plugin');
const dll = require('./webpack.config.dll');
const StyleLintPlugin = require('stylelint-webpack-plugin');

var os = require('os');
var HappyPack = require('happypack');
var happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });


const ASSET_PATH = process.env.ASSET_PATH || '/workflow';

module.exports = {
    context: path.resolve(__dirname, ''),
    entry: {
        index: "./src/index.tsx",
        vendor: dll.entry.lib
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: "[name].bundle.js?[chunkhash]",
        chunkFilename: "[name].bundle.js?[chunkhash]",
        publicPath: ASSET_PATH,
    },
    devServer: {
        contentBase: __dirname + "/src",
        historyApiFallback: {
            index: ASSET_PATH
        }
    },
    //devtool: 'cheap-source-map',
    devtool: 'inline-source-map',
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
    },
    plugins: [
        // require('precss'),
        // require('postcss-scss'),
        // require('autoprefixer'),
        new CaseSensitivePathsPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            filename: 'common.js',
        }),
        new HtmlWebpackPlugin(
            {
                title: 'Index',
                appPath: ASSET_PATH,
                filename: 'index.html',
                chunks: ['common', 'index', 'lib'],
                inject: 'body',
                template: './src/helper/index.html',
            }
        ),
        new copyWebpackPlugin([{
            from: path.resolve(__dirname, 'dll'),
            to: path.resolve(__dirname, 'dist'),
        }], {
                copyUnmodified: true
            }),
        new webpack.DllReferencePlugin({
            context: __dirname,
            name: 'lib_bundle',
            manifest: require('./dll/lib-manifest.json'),
        }),
        // only production
        // new webpack.optimize.UglifyJsPlugin({
        //     // 最紧凑的输出
        //     beautify: false,
        //     // 删除所有的注释
        //     comments: false,
        //     compress: {
        //         // 在UglifyJs删除没有用到的代码时不输出警告  
        //         warnings: false,
        //         // 删除所有的 `console` 语句
        //         // 还可以兼容ie浏览器
        //         drop_console: false,
        //         // 内嵌定义了但是只用到一次的变量
        //         collapse_vars: true,
        //         // 提取出出现多次但是没有定义成变量去引用的静态值
        //         reduce_vars: true,
        //     },
        //     //sourceMap: true,
        //     minimize: true
        // }),
        new webpack.DefinePlugin({
            'production': JSON.stringify(process.env.NODE_ENV) === 'production',
            'appPath': JSON.stringify('/dist'),
        }),
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: function () {
                    return {
                        plugins: [autoprefixer({ borwsers: ['Safari>1'] })],
                        syntax: postcssSCSS
                    }
                }
            }
        }),
        new ExtractTextPlugin({
            filename: "app.bundle.css",
            disable: false,
            allChunks: true
        }),
        //装入器的调试模式将在webpack 3或更高版本中删除。
        new webpack.LoaderOptionsPlugin({
            debug: true
        }),
        // new StyleLintPlugin({
        //     config: {
        //         // lint扩展自刚刚安装的stylelint-config-standard
        //         "extends": "stylelint-config-standard"
        //     },∂
        //     // 正则匹配想要lint监测的文件
        //     files: './**/*.s?(a|c)ss'
        // }),
        //自动打开浏览器页面
        // new openBrowserPlugin({
        //     url: 'http://127.0.0.1:8080/'
        // }),
        // new HappyPack({
        //     id: 'jsHappy',
        //     cache: false,
        //     threadPool: happyThreadPool,
        //     loaders: [{
        //         path: 'babel-loader',
        //         query: {
        //             cacheDirectory: '.webpack_cache',
        //             presets: [
        //                 'es2015',
        //                 'react'
        //             ]
        //         }
        //     }]
        // }),
        // //如果有单独提取css文件的话
        // new HappyPack({
        //     id: 'sassHappy',
        //     loaders: ['style-loader', 'css-loader', 'less-loader']
        // }),
    ],
    module: {
        rules: [
            {
                enforce: "pre",
                test: /\.js$/,
                exclude: /node_modules/,
                use: [{ "loader": "source-map-loader" }]
            },
            {
                enforce: 'pre',
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: [{ "loader": "source-map-loader" }]
            },
            {
                test: /\.js|tsx?$/,
                exclude: /node_modules/,
                use: [
                    { "loader": "react-hot-loader" },
                    { "loader": "babel-loader", "options": { "cacheDirectory": false } },
                    { "loader": "awesome-typescript-loader" },
                    //{ "loader": "HappyPack/loader", "options": { "id": "jsHappy" } },
                ],
            },
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: [
                        { "loader": "css-loader", "options": { "minimize": true } },
                        { "loader": "less-loader" },
                        //{ "loader": "postcss-loader" },
                        //{ "loader": "HappyPack/loader", "options": { "id": "sassHappy" } },
                    ],
                    publicPath: "/asset"
                }),
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: [
                        { "loader": "css-loader", "options": { "minimize": true } },
                        { "loader": "sass-loader", "options": { "sourceMap": true, "includePaths": ["./src/asset/style"] } },
                        { "loader": "postcss-loader" },
                    ],
                    publicPath: "/asset"
                })
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)(.+)?$/,
                use: [{
                    "loader": "file-loader",
                    "options": {
                        "name": "/fonts/[name].[ext]"
                    }
                }]
            },
            {
                test: /\.(png|jpeg|jpg)$/,
                use: [{
                    "loader": "url-loader",
                    "options": {
                        "limit": 8192,
                        "name": "/img/[name].[ext]"
                    }
                }]
            }
        ]
    }
};